package com.hodi.myfirstapp

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.hodi.myfirstapp.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {


    private lateinit var binding: ActivityMainBinding


    private val resultLauncher: ActivityResultLauncher<Intent> =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        result ->
            val code =result.resultCode
            val data = result.data
            val s = data?.getStringExtra("name")
            Log.i("MainActivity", "result data: $s")
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.menu_item1 -> {
                Toast.makeText(
                    this, "Menu Item 1 clicked",
                    Toast.LENGTH_SHORT
                ).show()
                supportActionBar?.title = "Menu Item 1 clicked"

            }

            R.id.menu_item2 -> Toast.makeText(this, "Menu Item 2 clicked", Toast.LENGTH_SHORT)
                .show()
        }
        return true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setSupportActionBar(findViewById(R.id.my_toolbar))
        binding.button1.setOnClickListener {
            val intent =  Intent(this, MainActivity2::class.java)
            startActivity(intent)
            Toast.makeText(this, "Button clicked", Toast.LENGTH_SHORT).show()
        }
        Log.d("MainActivity", "onCreate called")

    }

    fun toAt2(view: View) {
        val intent = Intent("com.hodi.myfirstapp.MainActivity4")
        intent.addCategory("com.hodi.myfirstapp.category4")
        intent.putExtra("name2", "Hello2")
        resultLauncher.launch(intent)
    }

    fun toLife(view: View) {
        val intent = Intent(this, MainActivity5::class.java)
        startActivity(intent)
    }

}